// reactHelpers.js
const React = require('react');
const ReactDOM = require('react-dom/client');
const ReactFlow = require('reactflow');

// 安全地暴露 ReactDOM API 到渲染进程
const reactHelpers = {
  
  // 创建 React 元素
  createElement: React.createElement,
  
  // 创建ReactFlow组件
  createReactFlowComponent: (props, children) => {
    return React.createElement(ReactFlow.ReactFlow, props, children);
  },
  
  // 创建ReactFlow子组件
  createBackground: (props) => {
    return React.createElement(ReactFlow.Background, props);
  },
  
  createControls: (props) => {
    return React.createElement(ReactFlow.Controls, props);
  },
  
  createMiniMap: (props) => {
    return React.createElement(ReactFlow.MiniMap, props);
  },
  
  // 工作流初始化函数
  initWorkflow: (canvas, workflowConfig) => {
    if (!canvas || !(canvas instanceof HTMLElement)) {
      throw new Error('Invalid canvas element provided for workflow initialization');
    }
    
    // 清空canvas内容
    canvas.innerHTML = '';
    
    const { nodes, edges, callbacks, nodeTypes } = workflowConfig;
    
    // 创建ReactFlow组件的子元素
    const children = [
      React.createElement(ReactFlow.Background, { key: 'background', variant: 'dots' }),
      React.createElement(ReactFlow.Controls, { key: 'controls' }),
      React.createElement(ReactFlow.MiniMap, { 
        key: 'minimap',
        style: { height: 120 },
        nodeColor: (node) => {
          const nodeType = node.data?.nodeType || 'default';
          return nodeTypes[nodeType]?.color || '#ccc';
        }
      })
    ];
    
    // 创建ReactFlow组件
    const ReactFlowComponent = React.createElement(ReactFlow.ReactFlow, {
      nodes: nodes,
      edges: edges,
      onNodesChange: callbacks.onNodesChange,
      onEdgesChange: callbacks.onEdgesChange,
      onConnect: callbacks.onConnect,
      onInit: callbacks.onInit,
      onNodeClick: callbacks.onNodeClick,
      fitView: true,
      style: { width: '100%', height: '100%' }
    }, children);
    
    // 创建并渲染根组件
    const root = ReactDOM.createRoot(canvas);
    root.render(ReactFlowComponent);
    
    return root;
  },
    // 检查React和ReactFlow是否可用
  isReactFlowAvailable: () => {
    return typeof React !== 'undefined' && 
           typeof ReactDOM !== 'undefined' && 
           typeof ReactFlow !== 'undefined';
  },
    // 更新ReactFlow实例
  updateReactFlowInstance: (reactFlowInstance, nodes, edges) => {
    if (reactFlowInstance) {
      // 使用setTimeout确保状态更新不会冲突
      setTimeout(() => {
        if (reactFlowInstance) {
          reactFlowInstance.setNodes([...nodes]);
          reactFlowInstance.setEdges([...edges]);
        }
      }, 10);
    }
  },
    // 清理React根实例
  unmountRoot: (root) => {
    if (root && typeof root.unmount === 'function') {
      try {
        root.unmount();
      } catch (error) {
        console.error('Error unmounting React root:', error);
      }
    }
  },
  
  // 重新初始化工作流（用于加载新数据时）
  reinitWorkflow: (canvas, workflowConfig) => {
    if (!canvas || !(canvas instanceof HTMLElement)) {
      throw new Error('Invalid canvas element provided for workflow reinitialization');
    }
    
    // 清空canvas内容
    canvas.innerHTML = '';
    
    const { nodes, edges, callbacks, nodeTypes } = workflowConfig;
    
    // 创建ReactFlow组件的子元素
    const children = [
      React.createElement(ReactFlow.Background, { key: 'background', variant: 'dots' }),
      React.createElement(ReactFlow.Controls, { key: 'controls' }),
      React.createElement(ReactFlow.MiniMap, { 
        key: 'minimap',
        style: { height: 120 },
        nodeColor: (node) => {
          const nodeType = node.data?.nodeType || 'default';
          return nodeTypes[nodeType]?.color || '#ccc';
        }
      })
    ];
    
    // 创建ReactFlow组件
    const ReactFlowComponent = React.createElement(ReactFlow.ReactFlow, {
      nodes: nodes,
      edges: edges,
      onNodesChange: callbacks.onNodesChange,
      onEdgesChange: callbacks.onEdgesChange,
      onConnect: callbacks.onConnect,
      onInit: callbacks.onInit,
      onNodeClick: callbacks.onNodeClick,
      fitView: true,
      style: { width: '100%', height: '100%' }
    }, children);
    
    // 创建并渲染根组件
    const root = ReactDOM.createRoot(canvas);
    root.render(ReactFlowComponent);
    
    return root;
  },
  
  // 获取ReactFlow项目坐标
  projectPosition: (reactFlowInstance, clientX, clientY, canvasBounds) => {
    if (reactFlowInstance && typeof reactFlowInstance.project === 'function') {
      return reactFlowInstance.project({
        x: clientX - canvasBounds.left,
        y: clientY - canvasBounds.top
      });
    }
    return {
      x: clientX - canvasBounds.left - 60,
      y: clientY - canvasBounds.top - 20
    };
  },
    // 调整ReactFlow视图
  fitView: (reactFlowInstance) => {
    if (reactFlowInstance && typeof reactFlowInstance.fitView === 'function') {
      reactFlowInstance.fitView();
    }
  },
  
  // 调试工具：获取ReactFlow实例的状态信息
  getReactFlowInstanceInfo: (reactFlowInstance) => {
    if (!reactFlowInstance) {
      return { available: false, methods: [] };
    }
    
    const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(reactFlowInstance))
      .filter(name => typeof reactFlowInstance[name] === 'function');
    
    return {
      available: true,
      methods: methods,
      hasSetNodes: typeof reactFlowInstance.setNodes === 'function',
      hasSetEdges: typeof reactFlowInstance.setEdges === 'function',
      hasFitView: typeof reactFlowInstance.fitView === 'function',
      hasProject: typeof reactFlowInstance.project === 'function'
    };
  }
};

module.exports = reactHelpers;
